const Koa = require("koa");
const app = new Koa();
const router = require('koa-router')();
const gameio = require("./gameio");
const custom_router = require("./router");
const url = require("url");
const net = require("net");

app.keys = ['im a newer secret', 'Gaubee', 'youdob inc.'];

router.get("/", (ctx, next) => {
  ctx.body = '十三水!没有BUG!';
});

custom_router.setup({
  router
});

app.use(async(ctx, next) => {
    const referer = ctx.headers.referer;
    if (referer) {
      const referer_url_info = url.parse(referer);
      const {
        protocol,
        hostname,
        host,
      } = referer_url_info;
      // 白名单可访问
      if (hostname === "localhost" ||
        net.isIPv4(hostname) ||
        hostname.endsWith(".youdob.com") ||
        hostname.endsWith(".youdob.org")) {
        const origin = protocol + "//" + host;
        ctx.set('Access-Control-Allow-Origin', origin);
        ctx.set('Access-Control-Allow-Credentials', true);
        ctx.set('Access-Control-Allow-Methods','POST, GET, OPTIONS, DELETE, PUT');
        ctx.set('Access-Control-Allow-Headers', 'Referer, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
      }
    }
    try {
      await next();
      if (ctx.body) {
        ctx.body = {
          status: "success",
          data: ctx.body
        }
      }
    } catch (err) {
      console.error(err instanceof Error ? err.stack : String(err))
      // will only respond with JSON
      ctx.status = err.statusCode || err.status || 500;
      ctx.body = {
        status: "error",
        msg: err instanceof Error ? err.message : String(err)
      };
    }
  })
  .use(router.routes())
  .use(router.allowedMethods());

const server = gameio.setup(app, (io) => {});

server.listen(3000);
